import json
import threading
import datetime
from time import sleep
import requests
from selenium.webdriver.chrome.options import Options
from selenium.webdriver import Chrome, ActionChains, Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service

# 获取当前日期和时间
now = datetime.datetime.now()

# 分别获取年、月、日，并将月和日格式化为两位字符串
year = now.year
month = f"{now.month:02d}"
day = f"{now.day:02d}"

# 计算后两天的日期
two_days_later = now + datetime.timedelta(days=2)

# 分别获取后两天的年、月、日，并将月和日格式化为两位字符串
year1 = two_days_later.year
month1 = f"{two_days_later.month:02d}"
day1 = f"{two_days_later.day:02d}"


def auto_reserve():
    # 设定任务执行时间
    target_time = '22:30:00'
    while True:
        # 获取当前时间
        current_time = datetime.datetime.now().strftime('%H:%M:%S')
        # 检查当前时间是否等于目标时间
        if current_time == target_time:
            # 执行任务
            while True:
                q = requests.post("http://icspace.lib.zjhu.edu.cn/ic-web/reserve", data=json.dumps(payload),
                                  headers=request_header)
                print(q.json())
                q = requests.post("http://icspace.lib.zjhu.edu.cn/ic-web/reserve", data=json.dumps(payload),
                                  headers=request_header)
                print(q.json())
                q = requests.post("http://icspace.lib.zjhu.edu.cn/ic-web/reserve", data=json.dumps(payload),
                                  headers=request_header)
                print(q.json())
            # 任务完成后退出循环


option = Options()
option.add_experimental_option("detach", True)
option.add_experimental_option('excludeSwitches', ['enable-automation'])

# 方法1：使用双反斜杠
chrome_driver_path = "C:\\Users\\12109\\Downloads\\chromedriver-win64\\chromedriver-win64\\chromedriver.exe"

# 方法2：使用原始字符串
chrome_driver_path = r"C:\Users\12109\Downloads\chromedriver-win64\chromedriver-win64\chromedriver.exe"

# 方法3：使用正斜杠
chrome_driver_path = "C:/Users/12109/Downloads/chromedriver-win64/chromedriver-win64/chromedriver.exe"

# Create a Service object
service = Service(executable_path=chrome_driver_path)

# Pass the Service object to the Chrome constructor
driver = Chrome(service=service, options=option)
# 登录
driver.get('https://rz.zjhu.edu.cn/cas/login?service=http://icspace.lib.zjhu.edu.cn')
# 防止selenium被检测
driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
    "source": """
    Object.defineProperty(navigator, 'webdriver', {
      get: () => false
    })
  """
})
name = driver.find_element(by=By.ID, value='username')
name.send_keys('2021082320')  # 输入学号
password = driver.find_element(by=By.ID, value='ppassword')
password.send_keys('@z12345678')  # 输入密码
login = driver.find_element(by=By.ID, value='dl')
login.click()  # 点击登录按钮
sleep(1)
cookie = driver.get_cookies()
cookie = cookie[0]
cookie = cookie.get('value')
request_header = {
    "Accept": "application/json, text/plain, */*",
    "Accept-Encoding": "gzip, deflate",
    "Accept-Language": "zh-CN,zh;q=0.9",
    "Connection": "keep-alive",
    "Host": "icspace.lib.zjhu.edu.cn",
    "lan": "1",
    "Referer": "http://icspace.lib.zjhu.edu.cn/",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.53 Safari/537.36"
}
request_header["Cookie"] = "ic-cookie=" + cookie
cookie = "ic-cookie=" + cookie
print(request_header)
response = requests.get("http://icspace.lib.zjhu.edu.cn/ic-web/auth/userInfo", headers=request_header)
token = (response.json()).get("data").get("token")
request_header = {
    "Accept": "application/json, text/plain, */*",
    "Accept-Encoding": "gzip, deflate",
    "Accept-Language": "zh-CN,zh;q=0.9",
    "Content-Length": "216",
    "Content-Type": "application/json;charset=UTF-8",
    "Connection": "keep-alive",
    "Host": "icspace.lib.zjhu.edu.cn",
    "lan": "1",
    "Origin": "http://icspace.lib.zjhu.edu.cn",
    "Referer": "http://icspace.lib.zjhu.edu.cn/",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.53 Safari/537.36"
}
request_header["Cookie"] = cookie
request_header["token"] = token
payload = {"sysKind": 8, "appAccNo": 74206, "memberKind": 1, "resvMember": [74206],
           "resvBeginTime": f"{year1}-{month1}-{day1} 8:00:00",
           "resvEndTime": f"{year1}-{month1}-{day1} 22:00:00",
           "testName": "", "captcha": "", "resvProperty": 0, "resvDev": [100458083], "memo": ""
           }
# 启动线程
t1 = threading.Thread(target=auto_reserve, name="MyThread1")
t1.start()
t1.join()
